package com.wtwd.device.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wtwd.device.model.CityData;
import com.wtwd.device.model.HeWeather;
import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class WeatherUtil {


    public static final String BASE_URL = "https://api.qweather.com/v7/weather/3d";

    public static final String CITY_URL = "https://geoapi.qweather.com/v2/city/lookup";

    public static final String HF_KEY = "a937c940beba48fdb6e874b7e24c5197";
    public static final String HF_USERNAME = "admin123";
    public static final String HF_PASSWORD = "Yuefit_admin";

    public static HeWeather getWeather(String cid, String language) {
        if (StringUtils.isEmpty(cid)) {
            return null;
        }
        String params = "key=" + HF_KEY + "&location=" + cid + "&lang=" + language;
        String response = HttpClients.sendGet(BASE_URL, params);
        HeWeather heWeather = transToHeWeather(response); //JSON.parseObject(response,HeWeather.class);
        System.out.println("getWeather response========" + response);
        return heWeather;
    }

    public static CityData getCityData(String lon, String lat, String language) {
        if (StringUtils.isEmpty(lon) || StringUtils.isEmpty(lon)) {
            return null;
        }
        String location = lon + "," + lat;
        String params = "key=" + HF_KEY + "&location=" + location + "&lang=" + language;
        String response = HttpClients.sendGet(CITY_URL, params);
        CityData cityData = transToCityData(response);//JSON.parseObject(response,CityData.class);
        System.out.println("getCityData response=========" + response);
        return cityData;
    }

    private static HeWeather transToHeWeather(String response) {
        HeWeather heWeather = null;
        JSONObject jsonObject = JSON.parseObject(response);
        if (jsonObject != null) {
            String code = jsonObject.getString("code");
            if (code.equals("200")) {
                heWeather = new HeWeather();
                List<HeWeather.HeWeather6Bean> heWeather6Beans = new ArrayList<>();
                HeWeather.HeWeather6Bean heWeather6Bean = new HeWeather.HeWeather6Bean();
                heWeather6Bean.setStatus("ok");
                List<HeWeather.HeWeather6Bean.DailyForecastBean> dailyForecastBeans = new ArrayList<>();
                JSONArray dailyArray = jsonObject.getJSONArray("daily");
                for (Iterator<Object> iterator = dailyArray.iterator(); iterator.hasNext(); ) {
                    JSONObject daily = (JSONObject) iterator.next();
                    HeWeather.HeWeather6Bean.DailyForecastBean dailyForecastBean = new HeWeather.HeWeather6Bean.DailyForecastBean();
                    dailyForecastBean.setCond_code_d(daily.getString("iconDay"));
                    dailyForecastBean.setCond_code_n(daily.getString("iconNight"));
                    dailyForecastBean.setCond_txt_d(daily.getString("textDay"));
                    dailyForecastBean.setCond_txt_n(daily.getString("textNight"));
                    dailyForecastBean.setDate(daily.getString("fxDate"));
                    dailyForecastBean.setHum(daily.getString("humidity"));
                    dailyForecastBean.setPcpn(daily.getString("precip"));
                    dailyForecastBean.setPres(daily.getString("pressure"));
                    dailyForecastBean.setTmp_max(daily.getString("tempMax"));
                    dailyForecastBean.setTmp_min(daily.getString("tempMin"));
                    dailyForecastBean.setUv_index(daily.getString("uvIndex"));
                    dailyForecastBean.setVis(daily.getString("vis"));
                    dailyForecastBean.setWind_deg(daily.getString("wind360Day"));
                    dailyForecastBean.setWind_dir(daily.getString("windDirDay"));
                    dailyForecastBean.setWind_sc(daily.getString("windScaleDay"));
                    dailyForecastBean.setWind_spd(daily.getString("windSpeedDay"));
                    dailyForecastBeans.add(dailyForecastBean);
                }
                heWeather6Bean.setDaily_forecast(dailyForecastBeans);
                String updateTime = jsonObject.getString("updateTime");//2021-01-19T14:35+08:00
                String locTime = updateTime.substring(0, updateTime.length() - 6);
                String zone = updateTime.substring(updateTime.length() - 6);
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
                SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                Calendar calendar = Calendar.getInstance();
                try {
                    HeWeather.HeWeather6Bean.UpdateBean updateBean = new HeWeather.HeWeather6Bean.UpdateBean();
                    Date locDate = format.parse(locTime);
                    calendar.setTime(locDate);
                    updateBean.setLoc(format1.format(calendar.getTime()));
                    calendar.add(Calendar.HOUR, Integer.parseInt(zone.split(":")[0]));
                    updateBean.setUtc(format1.format(calendar.getTime()));
                    heWeather6Bean.setUpdate(updateBean);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                heWeather6Beans.add(heWeather6Bean);
                heWeather.setHeWeather6(heWeather6Beans);
            }
        }
        return heWeather;
    }

    private static CityData transToCityData(String response) {
        CityData cityData = null;
        JSONObject jsonObject = JSON.parseObject(response);
        if (jsonObject != null) {
            String code = jsonObject.getString("code");
            if (code.equals("200")) {
                cityData = new CityData();
                List<CityData.HeWeather6Bean> heWeather6Beans = new ArrayList<>();
                CityData.HeWeather6Bean heWeather6Bean = new CityData.HeWeather6Bean();
                heWeather6Bean.setStatus("ok");
                List<CityData.HeWeather6Bean.BasicBean> basicBeans = new ArrayList<>();
                JSONObject locationJson = (JSONObject) jsonObject.getJSONArray("location").get(0);
                CityData.HeWeather6Bean.BasicBean basicBean = new CityData.HeWeather6Bean.BasicBean();
                basicBean.setAdmin_area(locationJson.getString("adm1"));
                basicBean.setCid(locationJson.getString("id"));
                basicBean.setCnty(locationJson.getString("country"));
                basicBean.setLat(locationJson.getString("lat"));
                basicBean.setLocation(locationJson.getString("name"));
                basicBean.setLon(locationJson.getString("lon"));
                basicBean.setParent_city(locationJson.getString("adm2"));
                basicBean.setType("city");
                basicBean.setTz(locationJson.getString("tz"));
                basicBeans.add(basicBean);
                heWeather6Bean.setBasic(basicBeans);
                heWeather6Beans.add(heWeather6Bean);
                cityData.setHeWeather6(heWeather6Beans);
            }
        }
        return cityData;
    }

}
